﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using _4T.BLL;
using _4T.Data;

namespace _4T
{
    public partial class CMS_ProfileFilterForm : System.Web.UI.Page
    {
        private List<string> imageArrayPath = new List<string>();
        private List<string> videoArrayPath = new List<string>();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["p"] != null)
            {
                if (!IsPostBack)
                {
                    Session["imageArrayPath"] = imageArrayPath;
                    Session["videoArrayPath"] = videoArrayPath;
                    //
                    LoadProfileInfo(Request.QueryString["p"].ToString());
                    hdfProfileInfoCode.Value = Request.QueryString["p"].ToString();
                    LoadVerifierList();
                    CMS_ProfileInfo info = new ProfileInfoBLL().GetProfileInfoByProfileInfoCode(Request.QueryString["p"].ToString());
                    if (info != null)
                    {
                        hplEdit.NavigateUrl = "CMS_ProfileInfoEdit.aspx?p=" + info.ProfileCode;
                    }
                }
            }
        }

        private void LoadProfileInfo(string profileInfoCode)
        {
            // Load patient info
            PatientInfoBLL patientBLL = new PatientInfoBLL();
            PatientInfo patient = patientBLL.GetPatientInfo(profileInfoCode);
            if (patient != null)
            {
                lbPatientName.Text = patient.PatientName;
                lbDOB.Text = patient.Birthday.ToShortDateString();
                ddlGender.SelectedValue = patient.Gender;
                lbIDNumber.Text = patient.IDNumber;
                lbPermAddr.Text = patient.PermanentAddress;
                lbTempAddr.Text = patient.TemporaryAddress;
                lblMobileNumber.Text = patient.MobileNumber;
                lbPhoneNumber.Text = patient.PhoneNumber;
                lbRepresentativeName.Text = patient.EmergencyRepresentative;
                lbRepresentativePhone.Text = patient.RepresentativePhoneNumber;
                lbLocalContactName.Text = patient.LocalContactPoint;
                lbLocalContactPhone.Text = patient.LocalContactPointPhoneNumber;
                lbMedicalStaff.Text = patient.LocalMedicalStaff;
                lbMedicalStaffPhone.Text = patient.LocalMedicalStaffPhoneNumber;
                lbMedicalFacility.Text = patient.MedicalFacility;
                lbNote.Text = patient.Note;
            }

            // Load medical info
            MedicalInfoBLL medicalBLL = new MedicalInfoBLL();
            MedicalInfo medical = medicalBLL.GetMedicalInfo(profileInfoCode);
            if (medical != null)
            {
                lblDiagnosis.Text = medical.Diagnosis;
                lbMedicalTime.Text = medical.MedicalTime.ToShortDateString();
                lbTreatmentMethod.Text = medical.TreatmentMethod;
                lbSituation.Text = medical.Situation;
                lbSupport.Text = medical.Support;
            }

            // Load info supplier info
            InfoSupplierInfoBLL infoSupplierBLL = new InfoSupplierInfoBLL();
            InfoSupplierInfo supplier = infoSupplierBLL.GetInfoSupplierInfo(profileInfoCode);
            if (supplier != null)
            {
                lbInfoSupplierName.Text = supplier.SupplierName;
                lbInfoSupplierPhone.Text = supplier.PhoneNumber;
                //lbPersonalCode.Text = supplier.PersonalCode;
                lbEmail.Text = supplier.Email;
            }

            // Load photo, video
            ProfileStageLink stage = new ProfileStageLinkBLL().GetProfileStageLinkByProfileCodeAndStage(profileInfoCode, 1);
            if (stage != null)
            {
                if (!string.IsNullOrEmpty(stage.PhotoLink))
                {
                    if (stage.PhotoLink.IndexOf(';') < 0)
                    {
                        ltrImage.Text = "<img src=\"" + stage.PhotoLink + "\"/>";
                    }
                    else
                    {
                        string[] photoLinks = stage.PhotoLink.Split(';');
                        for (int i = 0; i < photoLinks.Length; i++)
                        {
                            ltrImage.Text += "<img src=\"" + photoLinks[i] + "\"/><br/>";
                        }
                    }
                }

                if (!string.IsNullOrEmpty(stage.VideoLink))
                {
                    if (stage.PhotoLink.IndexOf(';') < 0)
                    {
                        Page.ClientScript.RegisterStartupScript(GetType(), "playvideo", "playvideo('" + stage.VideoLink + "');", true);
                    }
                    else
                    {
                        string[] videoLinks = stage.VideoLink.Split(';');
                        Page.ClientScript.RegisterStartupScript(GetType(), "playvideo", "playvideo('" + videoLinks[0] + "');", true);
                    }
                }
            }

            // Load video info if profile created by upload video
            CMS_VideoUploadInfo video = new ProfileBLL().GetVideoUploadInfo(profileInfoCode);
            if (video != null)
            {
                string station = video.Station;
                if (station == "guest")
                {
                    ltrVideoDesc.Text = "Video được upload từ mobile vào lúc " + video.UploadTime;
                }
                else
                {
                    ltrVideoDesc.Text = "Video được upload từ trạm " + station + " vào lúc " + video.UploadTime;
                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            string sessionImageUrl = ImageUrl;
            string sessionVideoUrl = VideoUrl;
            Session["imageArrayPath"] = null;
            Session["videoArrayPath"] = null;
            CMS_ProfileInfo info = new ProfileInfoBLL().GetProfileInfoByProfileInfoCode(hdfProfileInfoCode.Value);
            ProfileStatus status = new ProfileStatus();
            status.ProfileCode = hdfProfileInfoCode.Value;
            if (ddlFilterResult.SelectedValue == "0")
            {
                status.Stage = 2;
                status.Status = 2;
            }
            else
            {
                status.Stage = 3;
                status.Status = 0;
                status.Verifier = ddlVerifierList.SelectedValue;
            }
            try
            {
                DateTime dayOfBirth = new DateTime();

                try
                {
                    dayOfBirth = Convert.ToDateTime(lbDOB.Text);
                }
                catch
                {
                    dayOfBirth = DateTime.Now;
                }

                PatientInfo patient = new PatientInfo(lbPatientName.Text, dayOfBirth,
                    ddlGender.SelectedValue, lbIDNumber.Text, lbPermAddr.Text, lbTempAddr.Text,
                    lblMobileNumber.Text, lbPhoneNumber.Text, lbRepresentativeName.Text,
                    lbRepresentativePhone.Text, lbLocalContactName.Text, lbLocalContactPhone.Text,
                    lbMedicalStaff.Text, lbMedicalStaffPhone.Text, lbMedicalFacility.Text,
                    lbNote.Text);

                if (patient != null)
                {
                    DAL.PatientInfoDAL patientDAL = new DAL.PatientInfoDAL();
                    patientDAL.UpdatePatientInfo(patient.PatientName, patient.Birthday, patient.Gender, patient.IDNumber, patient.PermanentAddress, patient.TemporaryAddress, patient.MobileNumber, patient.PhoneNumber, patient.EmergencyRepresentative, patient.RepresentativePhoneNumber, patient.LocalContactPoint, patient.LocalContactPointPhoneNumber, patient.LocalMedicalStaff, patient.LocalMedicalStaffPhoneNumber, patient.MedicalFacility, patient.Note, Request.QueryString["p"].ToString());
                }
            }
            catch
            {

            }
            try
            {

                DateTime medicalTime = new DateTime();

                try
                {
                    medicalTime = Convert.ToDateTime(lbMedicalTime.Text);
                }
                catch
                {
                    medicalTime = DateTime.Now;
                }

                MedicalInfo medical = new MedicalInfo(lblDiagnosis.Text, medicalTime,
                    lbTreatmentMethod.Text, lbSituation.Text, lbSupport.Text, null);

                if (medical != null)
                {
                    DAL.MedicalInfoDAL medicalDAL = new DAL.MedicalInfoDAL();
                    medicalDAL.UpdateMedicalInfo(medical.Diagnosis, medical.MedicalTime, medical.TreatmentMethod, medical.Situation, medical.Support, medical.Note, Request.QueryString["p"].ToString());
                }
            }
            catch
            {
            }
            if (Session["User"] != null) status.Filter = Session["User"].ToString();
            new ProfileStatusBLL().UpdateProfileStatusWithProfileInfoCode(status);
            DateTime createdDate = new DateTime();

            try
            {
                if (!string.IsNullOrEmpty(txtCreatedDate.Text))
                    createdDate = Convert.ToDateTime(txtCreatedDate.Text);
            }
            catch
            {
                createdDate = DateTime.Now;
            }
            int result = new ProfileStageLinkBLL().InsertProfileStageLink(hdfProfileInfoCode.Value, 2, sessionVideoUrl, null, sessionImageUrl, txtDescription.Text, createdDate);

            if (result > 0) Response.Redirect("CMS_ProfileFilterList.aspx");
        }

        protected void ddlFilterResult_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlFilterResult.SelectedValue == "1")
            {
                ddlVerifierList.Enabled = true;
                LoadVerifierList();
            }
            else
            {
                ddlVerifierList.Enabled = false;
                ddlVerifierList.DataSource = null;
            }
        }

        private void LoadVerifierList()
        {
            ddlVerifierList.DataSource = new PersonalInfoBLL().GetPersonalListInSpecificRole(4);
            ddlVerifierList.DataTextField = "FullName";
            ddlVerifierList.DataValueField = "PersonalCode";
            ddlVerifierList.DataBind();
        }
        private string _imageUrl;
        public string ImageUrl
        {
            get
            {
                imageArrayPath = (Session["imageArrayPath"] as List<string>);
                if (imageArrayPath != null && imageArrayPath.Count > 0)
                {
                    foreach (var item in imageArrayPath)
                    {
                        _imageUrl += item;
                        break;
                    }
                    return _imageUrl;
                }
                else
                {
                    return string.Empty;
                }
            }
            set { _imageUrl = value; }
        }

        private string _videoUrl;
        public string VideoUrl
        {
            get
            {
                videoArrayPath = (Session["videoArrayPath"] as List<string>);
                if (videoArrayPath != null && videoArrayPath.Count != 0)
                {
                    foreach (var item in videoArrayPath)
                    {
                        _videoUrl += item;
                        break;
                    }
                    return _videoUrl;
                }
                else
                {
                    return string.Empty;
                }
            }
            set { _videoUrl = value; }
        }
    }
}